package com.clp.protocol.iec104.iec104.client.pipeline.check;

import com.clp.protocol.iec104.iec104.client.Master;
import com.clp.protocol.iec104.iec104.definition.ConstVal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 过滤器，检查消息内容合法性
 */
@Slf4j
public class CheckApduInHandler extends ChannelInboundHandlerAdapter {
    private final Master master;

    public CheckApduInHandler(Master master) {
        this.master = master;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf msgByteBuf = (ByteBuf) msg;
        if (msgByteBuf.readableBytes() == 0  // 没有信息内容
                || msgByteBuf.readableBytes() < ConstVal.APCI_LEN // 信息内容不足
                || msgByteBuf.getByte(0) != ConstVal.HEAD_VAL // 启动字符不符合
        ) {
            log.warn("报文无效，已丢弃！");
            msgByteBuf.release(); // 释放空间
            return;
        }
        ctx.fireChannelRead(msg);
    }

}
